import { TagField } from '@/pages/OrderModule/common/bizcomponents/TagField';
import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import { Form } from 'antd';
import { useMemo, useState, useEffect } from 'react';

/**
 * 排除标签弹窗
 * @param {*} props
 * @returns
 */
const ExcludeTagModal = (props) => {
  const { visible, onVisibleChange, onChange, value = {} } = props;
  const [form] = Form.useForm();

  const [commitSearch, setCommitSearch] = useState(value);
  const [tagList, setTagList] = useState([]);

  useEffect(() => {
    if(visible) {
      form.setFieldValue('excludeLabelIdArr', value?.excludeLabelIdArr);
    }
  }, [visible]);

  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  const excludeTagText = useMemo(() => {
    const connector = ',';
    const labelColorMap = {
      red: "红色标",
      blue: "蓝色标",
      yellow: "黄色标",
      purple: "紫色标",
      black: "黑色标"
    }
    if (commitSearch?.excludeLabelIdArr?.length > 0) {
      return tagList
        .filter((item) => commitSearch?.excludeLabelIdArr?.includes(item.id)).map((item) => (labelColorMap[item.name] || item.name))
        .join(connector);
    } else {
      return '';
    }
  }, [tagList, commitSearch]);

  const initialValues = commitSearch;

  return (
    <CommonModal
      width={840}
      title={{
        title: '排除标签',
      }}
      open={visible}
      onCancel={(e) => {
        onVisibleChange?.(false);
        setCommitSearch(value);
        form.setFieldValue('excludeLabelIdArr', value?.excludeLabelIdArr);
      }}
      onOk={(e) => {
        onVisibleChange?.(false);
        triggerChange?.({ ...commitSearch, excludeTagText });
      }}
    >
      <CommonForm
        formProps={{
          onValuesChange(changedValues, values) {
            setCommitSearch(values);
          },
          form,
          initialValues,
        }}
        columns={[
          {
            slot: <TagField setTagList={setTagList} fieldKey={'excludeLabelIdArr'} />,
          },
        ]}
      />
    </CommonModal>
  );
};
export default ExcludeTagModal;
